﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Infrastructure;
using Infrastructure.Dao;
using ServiceStack;
using SqlSugar;
using DormMS.Common;
using DormMS.IService;
using DormMS.Model;
using DormMS.Model.Enum;
using DormMS.Model.SearchModels;
using DormMS.Model.ViewModels;
using Infrastructure.Tool;

namespace DormMS.Service
{
    public class ProductService : IProductService
    {
        protected IProductCategoryService productcategoryservice;
        protected ICommonAreaService areaservice;

        public ProductService(IProductCategoryService _productcategoryservice, ICommonAreaService _areaservice)
        {
            productcategoryservice = _productcategoryservice;
            areaservice = _areaservice;
        }

        public List<ProductResponse> ProductManage(ProductSearchModel search, out int total)
        {
            using (var Db = DbConfig.GetInstance())
            {
                Db.CurrentFilterKey = "";
                Sqlable sable = Db.Sqlable().From<Product>("P");
                sable.Join<Product_Spec>("PS", "PS.ProductSku", "P.Sku", JoinType.Left);
                sable.Join<Product_Category>("PC", "PC.Id", "P.CategoryId", JoinType.Left);
                sable.Join<Product_Category>("PC1", "PC1.Id", "PC.ParentId", JoinType.Left);
                sable.Where(" P.IsDeleted=0 AND PS.IsDeleted=0 ");
                if (!search.Keywords.IsNullOrEmpty())
                {
                    sable.Where(" (P.Name like @Name or P.Sku like @Sku or PS.BarCode like @BarCode) ");
                }

                if (search.FirstCategoryIdParm > 0)
                {
                    sable.Where(" PC1.Id=@FirstCategoryId ");
                    if (search.SecondCategoryIdParm > 0)
                    {
                        sable.Where(" PC.Id=@SecondCategoryId ");
                    }
                }

                if (search.IsDisplayParm > 0)
                {
                    sable.Where(" P.IsDisplay=@IsDisplay ");
                }

                if (!search.OrderByFields.IsNullOrEmpty())
                {
                    search.OrderByFields = search.OrderByFields.Contains("CanSaleStock") ? search.OrderByFields.Replace("CanSaleStock", "SUM(PS.Stock-PS.WaitSendStock)") : search.OrderByFields;
                }
                else
                {
                    search.OrderByFields = "P.Id DESC";
                }

                var pars = new { Name = "%" + search.Keywords + "%", Sku = "%" + search.Keywords + "%", BarCode = "%" + search.Keywords + "%", FirstCategoryId = search.FirstCategoryIdParm, SecondCategoryId = search.SecondCategoryIdParm, IsDisplay = (search.IsDisplayParm == 1 ? 1 : 0) };
                sable.GroupBy = "GROUP BY P.Id";
                total = sable.SelectToList<Product>("P.Id", pars).Count;
                //total = sable.Count(pars);
                sable.GroupBy = "GROUP BY P.Id,P.Sku,P.AddTime,P.FavoriteCount,P.ImgUrl,P.IsDisplay,P.IsRecommend,P.Name,P.SaleCount,P.Sort,PC1.CategoryName,PC.CategoryName";
                var list = sable.SelectToPageList<ProductResponse>("P.Id,P.Sku,SUM(PS.Stock) AS 'TotalStock',MIN(CASE WHEN PS.Stock>0 THEN PS.Price END) AS 'Price',P.AddTime,P.FavoriteCount,P.ImgUrl,P.IsDisplay,P.IsRecommend,P.Name,P.SaleCount,P.Sort,PC1.CategoryName+'-'+PC.CategoryName AS 'CategoryNameList',SUM(PS.Stock-PS.WaitSendStock) AS 'CanSaleStock'", search.OrderByFields, search.Skip / search.Take + 1, search.Take, pars);
                return list;
            }
        }

        public List<SpecResponse> GetProductSpecLsit(ProductSearchModel search, ref int total)
        {
            using (var Db = DbConfig.GetInstance())
            {
                Db.CurrentFilterKey = "FalseDelteJoin";
                string where = "p.IsDisplay=1 and (m.Stock- m.WaitSendStock)>0 ";
                if (!search.Keywords.IsNullOrEmpty())
                {
                    where += " and p.Name like '%" + search.Keywords + "%' ";
                }
                if (search.FirstCategoryIdParm > 0)
                {
                    where += " and pc1.Id=" + search.FirstCategoryIdParm;
                    if (search.SecondCategoryIdParm > 0)
                    {
                        where += " and pc.Id = " + search.SecondCategoryIdParm;
                    }
                }

                var data = Db.Queryable<Product_Spec>().JoinTable<Product>((m, p) => m.ProductSku == p.Sku).JoinTable<Product_Spec, Product, Product_Category>((m, p, pc) => p.CategoryId == pc.Id).JoinTable<Product_Spec, Product_Category, Product_Category>((m, pc, pc1) => pc.ParentId == pc1.Id)
                    .Where(where).Select<Product_Spec, Product, Product_Category, Product_Category, SpecResponse>((m, p, pc, pc1) => new SpecResponse
                    {
                        Id = m.Id,
                        ProductId = p.Id,
                        Stock = m.Stock,
                        Name = p.Name,
                        SpecIds = m.SpecIds,
                        SpecNames = m.SpecNames,
                        WaitSendStock = m.WaitSendStock,
                        ImgUrl = p.ImgUrl,
                        Price = m.Price,
                        MarketPrice = m.MarketPrice,
                        CostPrice = m.CostPrice,
                        ProductWeight = m.ProductWeight,
                        FreightTemplateId = p.FreightTemplateId,
                        ProductSku = p.Sku
                    }).OrderBy(m => m.AddTime, OrderByType.Desc).ToPageList(search.Skip / search.Take + 1, search.Take, ref total);

                return data;
            }
        }


        public List<Product> ProductSelect(ProductSearchModel search, out int total)
        {
            using (var Db = DbConfig.GetInstance())
            {
                Db.CurrentFilterKey = "";
                Sqlable sable = Db.Sqlable().From<Product>("P");
                sable.Join<Product_Spec>("PS", "PS.ProductSku", "P.Sku", JoinType.Left);
                sable.Join<Product_Category>("PC", "PC.Id", "P.CategoryId", JoinType.Left);
                sable.Join<Product_Category>("PC1", "PC1.Id", "PC.ParentId", JoinType.Left);
                sable.Where(" P.IsDeleted=0 AND PS.IsDeleted=0 AND P.IsDisplay=1 ");
                if (!search.Keywords.IsNullOrEmpty())
                {
                    sable.Where(" (P.Name like @Name or P.Sku like @Sku or PS.BarCode like @BarCode) ");
                }

                if (search.FirstCategoryIdParm > 0)
                {
                    sable.Where(" PC1.Id=@FirstCategoryId ");
                    if (search.SecondCategoryIdParm > 0)
                    {
                        sable.Where(" PC.Id=@SecondCategoryId ");
                    }
                }


                search.OrderByFields = "P.Sort Desc,P.Id DESC";

                var pars = new { Name = "%" + search.Keywords + "%", Sku = "%" + search.Keywords + "%", BarCode = "%" + search.Keywords + "%", FirstCategoryId = search.FirstCategoryIdParm, SecondCategoryId = search.SecondCategoryIdParm };
                sable.GroupBy = "GROUP BY P.Id,P.Name,P.Sku,P.Price,P.MarketPrice,P.ImgUrl,P.Sort";
                total = sable.SelectToList<Product>("P.Id", pars).Count;
                var list = sable.SelectToPageList<Product>("P.Id,P.Name,P.Sku,P.Price,P.MarketPrice,P.ImgUrl,P.Sort", search.OrderByFields, search.Skip / search.Take + 1, search.Take, pars);
                list.ForEach(m =>
                {
                    var speclist = Db.Queryable<Product_Spec>().Where(w => w.ProductSku == m.Sku && w.IsDeleted == false && w.Stock - w.WaitSendStock > 0).ToList() ?? new List<Product_Spec>();
                    if (speclist != null && speclist.Count > 0)
                    {
                        m.Price = speclist.Min(s => s.Price);
                        m.MarketPrice = speclist.Max(s => s.MarketPrice);
                        m.TotalStock = speclist.Sum(s => s.Stock - s.WaitSendStock);
                    }
                });
                return list;
            }
        }


        public List<Product_SpecType> GetProductSpecType()
        {
            using (var Db = DbConfig.GetInstance())
            {
                return Db.Queryable<Product_SpecType>().ToList();
            }
            
        }

        public ProductEditResponse ProductEdit(string Sku)
        {
            var response = new ProductEditResponse();
            using (var Db = DbConfig.GetInstance())
            {
                if (!Sku.IsNullOrEmpty() && Sku != "0")
                {
                    //产品主信息
                    var product = Db.Queryable<Product>().SingleOrDefault(m => m.Sku == Sku);
                    if (product == null || product.Id == 0)
                    {
                        return response;
                    }

                    response.ProductMain = product.ConvertTo<ProductInfo>();
                    response.ProductMain.SubImgUrls = product.ImgUrls.FromJson<List<string>>();

                    var category = Db.Queryable<Product_Category>().SingleOrDefault(m => m.Id == product.CategoryId);
                    response.ProductMain.FirstCategoryId = category.ParentId;

                    //规格模版信息
                    var tempresponselist = new List<SpecTemplateResponse>();
                    var spectemplist = Db.Queryable<Product_SpecTemplate>().Where(m => m.SpecTypeId == product.SpecTypeId).ToList();
                    if (spectemplist != null && spectemplist.Count > 0)
                    {
                        spectemplist.ForEach(m =>
                        {
                            var spectemp = m.ConvertTo<SpecTemplateResponse>();
                            spectemp.SpecItemResponseList = Db.Queryable<Product_SpecTemplateItem>().Where(t => t.SpecTemplateId == m.Id).ToList();
                            tempresponselist.Add(spectemp);
                        });
                    }
                    response.SpecTemplateResponse = tempresponselist;

                    //规格信息
                    var speclist = Db.Queryable<Product_Spec>().Where(m => m.ProductSku == Sku).ToList();
                    var specresponse = new List<SpecResponse>();
                    var choosespecitemIds = new List<int>();
                    if (speclist != null && speclist.Count > 0)
                    {
                        speclist.ForEach(m =>
                        {
                            choosespecitemIds.AddRange(m.SpecIds.FromJson<List<int>>());
                            var specitem = m.ConvertTo<SpecResponse>();
                            specitem.SpecItemList = Db.Queryable<Product_SpecTemplateItem>().In(t => t.Id, m.SpecIds.FromJson<List<int>>()).OrderBy(o => o.SpecTemplateId).ToList();
                            specresponse.Add(specitem);
                        });

                        response.SpecList = specresponse.OrderBy(o => o.SpecItemList[0].Id).ToList();
                    }
                    //已选择的规格项
                    if (choosespecitemIds.Count == 0)
                    {
                        response.ChooseSpecItemList = new List<Product_SpecTemplateItem>();
                    }
                    else
                    {
                        response.ChooseSpecItemList = Db.Queryable<Product_SpecTemplateItem>().In(t => t.Id, choosespecitemIds.Distinct().ToList()).OrderBy(o => o.Id).ToList();
                    }

                    //已选择规格模版
                    if (response.ChooseSpecItemList.Count == 0)
                    {
                        response.ChooseSpecTemplateList = new List<Product_SpecTemplate>();
                    }
                    else
                    {
                        response.ChooseSpecTemplateList = Db.Queryable<Product_SpecTemplate>().In(i => i.Id, response.ChooseSpecItemList.Select(s => s.SpecTemplateId).Distinct().ToList()).ToList();
                    }
                }
                else
                {
                    response.ProductMain = new ProductInfo { SubImgUrls = new List<string>() };
                    response.SpecList = new List<SpecResponse>();
                    response.ChooseSpecItemList = new List<Product_SpecTemplateItem>();
                    response.ChooseSpecTemplateList = new List<Product_SpecTemplate>();
                    response.SpecTemplateResponse = new List<SpecTemplateResponse>();
                }

                //规格类型下拉框
                var spectypelist = Db.Queryable<Product_SpecType>().ToList();
                response.SpecTypeList = spectypelist ?? new List<Product_SpecType>();

                //产品分类下拉框
                response.CategoryList = productcategoryservice.GetCategoryList();

                //运费模版下拉框
                response.FreightList = Db.Queryable<FreightTemplate>().ToList();


                return response;
            }
        }

        public SpecResponse GetProduct_SpecInfo(int Id)
        {
            using (var Db = DbConfig.GetInstance())
            {
                Db.CurrentFilterKey = "FalseDelteJoin";
                return Db.SqlQuery<SpecResponse>("select m.*,p.ImgUrl,p.Id as ProductId,p.Name,p.CategoryId,p.IsAllowUsePoints,p.UsePointRate,p.IsAllowUseCoupon,p.UniformFreight,p.FreightTemplateId from Product_Spec m inner join Product p on m.ProductSku=p.Sku where m.Id=" + Id + " and p.IsDisplay=1").FirstOrDefault();
            }
        }


        public GetFreightInfoResponse GetFreightInfo(int Id)
        {
            var response = new GetFreightInfoResponse();
            if (Id == 0)
                return response;

            response = BaseService.LoadEntity<FreightTemplate>(m => m.Id == Id).ConvertTo<GetFreightInfoResponse>();

            var freightdetail = new List<FreightTemplateDetails>();
            BaseService.LoadEntities<FreightTemplateDetail>(m => m.FreightTemplateId == Id).ForEach(n => freightdetail.Add(n.ConvertTo<FreightTemplateDetails>()));
            freightdetail.ForEach(m => m.AreaNames = (m.AreaIds.FromJson<List<int>>().Contains(-1) ? new List<string> { "全国默认运费" } : areaservice.GetAreaListByIds(m.AreaIds.FromJson<List<int>>()).Select(s => s.Name).ToList()));
            response.FreightDetail = freightdetail;
            return response;
        }


        public SpecTypeChangeResponse ChangeSpecType(string Sku, int specTypeId)
        {
            using (var Db = DbConfig.GetInstance())
            {
                var response = new SpecTypeChangeResponse();

                //规格模版信息
                var tempresponselist = new List<SpecTemplateResponse>();
                var spectemplist = Db.Queryable<Product_SpecTemplate>().Where(m => m.SpecTypeId == specTypeId).ToList();
                if (spectemplist != null && spectemplist.Count > 0)
                {
                    spectemplist.ForEach(m =>
                    {
                        var spectemp = m.ConvertTo<SpecTemplateResponse>();
                        spectemp.SpecItemResponseList = Db.Queryable<Product_SpecTemplateItem>().Where(t => t.SpecTemplateId == m.Id).ToList();
                        tempresponselist.Add(spectemp);
                    });
                }
                response.SpecTemplateResponse = tempresponselist;

                var product = Db.Queryable<Product>().SingleOrDefault(m => m.Sku == Sku);
                if (product == null || product.Id == 0)
                {
                    response.SpecList = new List<SpecResponse>();
                    response.ChooseSpecItemList = new List<Product_SpecTemplateItem>();
                    response.ChooseSpecTemplateList = new List<Product_SpecTemplate>();
                    return response;
                }

                if (product.SpecTypeId == specTypeId)
                {
                    //规格信息
                    var speclist = Db.Queryable<Product_Spec>().Where(m => m.ProductSku == Sku).ToList();
                    var specresponse = new List<SpecResponse>();
                    var choosespecitemIds = new List<int>();
                    if (speclist != null && speclist.Count > 0)
                    {
                        speclist.ForEach(m =>
                        {
                            choosespecitemIds.AddRange(m.SpecIds.FromJson<List<int>>());
                            var specitem = m.ConvertTo<SpecResponse>();
                            specitem.SpecItemList = Db.Queryable<Product_SpecTemplateItem>().In(t => t.Id, m.SpecIds.FromJson<List<int>>()).OrderBy(o => o.SpecTemplateId).ToList();
                            specresponse.Add(specitem);
                        });
                    }
                    response.SpecList = specresponse;

                    //已选择的规格项
                    if (choosespecitemIds.Count == 0)
                    {
                        response.ChooseSpecItemList = new List<Product_SpecTemplateItem>();
                    }
                    else
                    {
                        response.ChooseSpecItemList = Db.Queryable<Product_SpecTemplateItem>().Where(t => choosespecitemIds.Contains(t.Id)).OrderBy(o => o.Id).ToList();
                    }

                    //已选择规格模版
                    if (response.ChooseSpecItemList.Count == 0)
                    {
                        response.ChooseSpecTemplateList = new List<Product_SpecTemplate>();
                    }
                    else
                    {
                        response.ChooseSpecTemplateList = Db.Queryable<Product_SpecTemplate>().In(i => i.Id, response.ChooseSpecItemList.Select(s => s.SpecTemplateId).Distinct().ToList()).ToList();
                    }
                    return response;
                }

                response.SpecList = new List<SpecResponse>();
                response.ChooseSpecItemList = new List<Product_SpecTemplateItem>();
                response.ChooseSpecTemplateList = new List<Product_SpecTemplate>();
                return response;
            }
        }


        public ChooseSpecItemResponse ChooseSpecItem(string Sku, List<Product_SpecTemplateItem> chooseSpecItemList)
        {
            using (var Db = DbConfig.GetInstance())
            {
                var response = new ChooseSpecItemResponse();
                if (chooseSpecItemList == null || chooseSpecItemList.Count == 0)
                {
                    response.ChooseSpecTemplateList = new List<Product_SpecTemplate>();
                    response.SpecList = new List<SpecResponse>();
                    return response;
                }

                //已选规格模版
                response.ChooseSpecTemplateList = Db.Queryable<Product_SpecTemplate>().In(i => i.Id, chooseSpecItemList.Select(s => s.SpecTemplateId).ToList()).ToList();

                //根据已选规格项重新排列规格
                ArrayList arrayList = new ArrayList();
                var specitemgroupbytempId = chooseSpecItemList.GroupBy(g => g.SpecTemplateId);
                foreach (var group in specitemgroupbytempId)
                {
                    //var groupids = chooseSpecItemList.Where(w => w.SpecTemplateId == group.Key).Select(s => s.Id).ToArray();
                    //arrayList.Add(groupids);
                    arrayList.Add(chooseSpecItemList.Where(w => w.SpecTemplateId == group.Key).Select(s => s.Id).ToArray());
                }

                var specGroup = GenerateTrRow(arrayList);
                var specresponse = new List<SpecResponse>();
                if (specGroup.Count > 0)
                {
                    foreach (int[] groupitem in specGroup)
                    {
                        var specitem = new SpecResponse();
                        specitem.SpecItemList = chooseSpecItemList.Where(w => groupitem.Contains(w.Id)).OrderBy(o => o.SpecTemplateId).ToList();
                        //如果已选规格组合则返回现有数据，否则重置数据
                        if (!Sku.IsNullOrEmpty() && Sku != "0")
                        {
                            var specids = specitem.SpecItemList.OrderBy(o => o.SpecTemplateId).Select(s => s.Id).ToList().ToJson();
                            var spec = Db.Queryable<Product_Spec>().SingleOrDefault(m => m.SpecIds == specids && m.ProductSku == Sku);
                            if (spec != null && spec.Id > 0)
                            {
                                specitem = spec.ConvertTo<SpecResponse>();
                                specitem.SpecItemList = chooseSpecItemList.Where(w => groupitem.Contains(w.Id)).OrderBy(o => o.SpecTemplateId).ToList();
                            }
                        }
                        specresponse.Add(specitem);
                    }
                }
                response.SpecList = specresponse;

                return response;
            }
        }

        private ArrayList GenerateTrRow(ArrayList SpecArrayList)
        {
            var specGroup = new ArrayList();
            if (SpecArrayList != null && SpecArrayList.Count > 0)
            {
                var tempGroup = new ArrayList();
                int[] firstSpecArrayList = (int[])SpecArrayList[0];
                for (int i = 0; i < firstSpecArrayList.Length; i++)
                {
                    tempGroup.Add(new int[] { firstSpecArrayList[i] });
                }
                SpecArrayList.RemoveAt(0);

                specGroup = GenerateGroup(SpecArrayList, tempGroup);
            }

            return specGroup;
        }

        private ArrayList GenerateGroup(ArrayList SpecArrayList, ArrayList tempGroup)
        {
            if (SpecArrayList != null && SpecArrayList.Count > 0)
            {
                for (int i = 0; i < SpecArrayList.Count; i++)
                {
                    int[] s = (int[])SpecArrayList[i];
                    ArrayList newTempGroup = new ArrayList();
                    for (int j = 0; j < tempGroup.Count; j++)
                    {
                        for (int k = 0; k < s.Length; k++)
                        {
                            var tempOne = new List<int>();
                            for (int x = 0; x < ((int[])tempGroup[j]).Length; x++)
                            {
                                tempOne.Add(((int[])tempGroup[j])[x]);
                            }
                            tempOne.Add(s[k]);
                            newTempGroup.Add(tempOne.ToArray());
                        }
                    }
                    if (newTempGroup.Count > 0)
                    {
                        tempGroup = newTempGroup;
                    }
                }
            }
            return tempGroup;
        }


        public Result ProductEditSubmit(ProductInfo ProductMain, List<SpecResponse> SpecList, int currentUserId, string ip)
        {
            if (ProductMain == null || SpecList == null || SpecList.Count == 0)
            {
                return Result.Failure("数据不完整，无法保存");
            }

            using (var Db = DbConfig.GetInstance())
            {
                var product = ProductMain.ConvertTo<Product>();
                product.ImgUrls = ProductMain.SubImgUrls.ToJson();
                product.TotalStock = SpecList.Sum(s => s.Stock);
                product.MarketPrice = SpecList.Max(s => s.MarketPrice);
                product.Price = SpecList.Min(s => s.Price);

                //判断排序重复
                //if (Db.Queryable<Product>().Where(m => m.Sort == product.Sort && m.Id != product.Id).Count() > 0)
                //{
                //    return Result.Failure("排序不能重复");
                //}

                //新增
                if (product.Id == 0)
                {
                    product.IsDisplay = false;
                    product.AddUserId = currentUserId;
                    int productid = Db.Insert(product, true).ObjToInt();
                    if (productid == 0)
                    {
                        return Result.Failure("数据保存失败");
                    }

                    product = Db.Queryable<Product>().Single(m => m.Id == productid);

                    #region 产品操作轨迹
                    Db.Insert(new Product_Record
                    {
                        AddUserId = currentUserId,
                        ChangeType = (int)ProductRecordTypeEnum.新增,
                        IP = ip,
                        ProductId = productid,
                        Remark = ModelHelper.GetObjCompareString(new Product(), product)
                    });
                    #endregion

                    SpecList.ForEach(m =>
                    {
                        var spec = m.ConvertTo<Product_Spec>();
                        spec.AddUserId = currentUserId;
                        spec.ProductSku = product.Sku;
                        spec.SpecIds = m.SpecItemList.OrderBy(o => o.SpecTemplateId).Select(s => s.Id).ToList().ToJson();
                        spec.SpecNames = m.SpecItemList.OrderBy(o => o.SpecTemplateId).Select(s => s.SpecItemName).ToList().ToJson();
                        int specid = Db.Insert(spec, true).ObjToInt();
                        spec = Db.Queryable<Product_Spec>().Single(s => s.Id == specid);

                        #region 产品操作轨迹
                        Db.Insert(new Product_Record
                        {
                            AddUserId = currentUserId,
                            ChangeType = (int)ProductRecordTypeEnum.新增,
                            IP = ip,
                            ProductId = productid,
                            Remark = ModelHelper.GetObjCompareString(new Product_Spec(), spec)
                        });
                        #endregion
                    });

                }
                //编辑
                else
                {
                    product.EditTime = DateTime.Now;
                    product.EditUserId = currentUserId;

                    var oldproduct = Db.Queryable<Product>().Single(m => m.Id == product.Id);
                    if (Db.Update(product))
                    {
                        #region 产品操作轨迹
                        Db.Insert(new Product_Record
                        {
                            AddUserId = currentUserId,
                            ChangeType = (int)ProductRecordTypeEnum.修改,
                            IP = ip,
                            ProductId = product.Id,
                            Remark = ModelHelper.GetObjCompareString(oldproduct, product)
                        });
                        #endregion

                        //老数据中无效数据删除
                        var oldspeclist = Db.Queryable<Product_Spec>().Where(m => m.ProductSku == product.Sku).ToList();
                        if (oldspeclist != null && oldspeclist.Count > 0)
                        {
                            oldspeclist.ForEach(m =>
                            {
                                if (!SpecList.Any(a => a.Id == m.Id))
                                {
                                    var oldspec = m;
                                    m.IsDeleted = true;
                                    m.EditTime = DateTime.Now;
                                    m.EditUserId = currentUserId;
                                    Db.Update(m);

                                    #region 产品操作轨迹
                                    Db.Insert(new Product_Record
                                    {
                                        AddUserId = currentUserId,
                                        ChangeType = (int)ProductRecordTypeEnum.修改,
                                        IP = ip,
                                        ProductId = product.Id,
                                        Remark = ModelHelper.GetObjCompareString(oldspec, m)
                                    });
                                    #endregion
                                }
                            });
                        }

                        SpecList.ForEach(m =>
                        {
                            var spec = m.ConvertTo<Product_Spec>();
                            spec.SpecIds = m.SpecItemList.OrderBy(o => o.SpecTemplateId).Select(s => s.Id).ToList().ToJson();
                            spec.SpecNames = m.SpecItemList.OrderBy(o => o.SpecTemplateId).Select(s => s.SpecItemName).ToList().ToJson();

                            if (spec.Id > 0)
                            {
                                var oldspec = Db.Queryable<Product_Spec>().Single(s => s.Id == spec.Id);

                                spec.EditTime = DateTime.Now;
                                spec.EditUserId = currentUserId;
                                spec.IsDeleted = false;
                                if (Db.Update(spec))
                                {
                                    #region 产品操作轨迹
                                    Db.Insert(new Product_Record
                                    {
                                        AddUserId = currentUserId,
                                        ChangeType = (int)ProductRecordTypeEnum.修改,
                                        IP = ip,
                                        ProductId = product.Id,
                                        Remark = ModelHelper.GetObjCompareString(oldspec, spec)
                                    });
                                    #endregion
                                }
                            }
                            else
                            {
                                spec.ProductSku = product.Sku;
                                spec.AddUserId = currentUserId;
                                if (Db.Insert(spec).ObjToInt() > 0)
                                {
                                    #region 产品操作轨迹
                                    Db.Insert(new Product_Record
                                    {
                                        AddUserId = currentUserId,
                                        ChangeType = (int)ProductRecordTypeEnum.新增,
                                        IP = ip,
                                        ProductId = product.Id,
                                        Remark = ModelHelper.GetObjCompareString(new Product_Spec(), spec)
                                    });
                                    #endregion
                                }
                            }
                        });
                    }
                    else
                    {
                        return Result.Failure("数据保存失败");
                    }
                }
                return Result.Success();
            }
        }


        public Result DelProduct(string Sku, int currentUserId, string ip)
        {
            using (var Db = DbConfig.GetInstance())
            {
                var product = Db.Queryable<Product>().Single(m => m.Sku == Sku);
                if (product == null || product.Id == 0)
                {
                    return Result.Failure("该数据不存在，请刷新后重试");
                }
                var oldproduct = product;
                product.IsDeleted = true;
                product.EditTime = DateTime.Now;
                product.EditUserId = currentUserId;
                if (Db.Update(product))
                {
                    var prospec = Db.Queryable<Product_Spec>().Where(m => m.ProductSku == Sku).ToList();
                    foreach (var item in prospec)
                    {
                        item.IsDeleted = true;
                        Db.Update(item);
                    }


                    #region 产品操作轨迹
                    Db.Insert(new Product_Record
                    {
                        AddUserId = currentUserId,
                        ChangeType = (int)ProductRecordTypeEnum.删除,
                        IP = ip,
                        ProductId = product.Id,
                        Remark = ModelHelper.GetObjCompareString(oldproduct, product)
                    });
                    #endregion
                    return Result.Success();
                }
                else
                {
                    return Result.Failure("数据更新失败，请刷新后重试");
                }
            }
        }



        public Result ChangeDisplay(string Sku, int currentUserId, string ip)
        {
            using (var Db = DbConfig.GetInstance())
            {
                var product = Db.Queryable<Product>().Single(m => m.Sku == Sku);
                if (product == null || product.Id == 0)
                {
                    return Result.Failure("该数据不存在，请刷新后重试");
                }
                var oldproduct = product;
                product.IsDisplay = !product.IsDisplay;
                product.EditTime = DateTime.Now;
                product.EditUserId = currentUserId;
                if (Db.Update(product))
                {
                    #region 产品操作轨迹
                    Db.Insert(new Product_Record
                    {
                        AddUserId = currentUserId,
                        ChangeType = (int)ProductRecordTypeEnum.上下架,
                        IP = ip,
                        ProductId = product.Id,
                        Remark = ModelHelper.GetObjCompareString(oldproduct, product)
                    });
                    #endregion
                    return Result.Success();
                }
                else
                {
                    return Result.Failure("数据更新失败，请刷新后重试");
                }
            }
        }

        /// <summary>
        /// 产品评论管理
        /// </summary>
        /// <param name="search"></param>
        /// <param name="total"></param>
        /// <returns></returns>
        public List<V_Product_Comment> CommentManage(ProductCommetSearchModel search, out int total)
        {
            using (var Db = DbConfig.GetInstance())
            {
                Sqlable sable = Db.Sqlable().From<Product_Comment>("");
                if (!search.Keywords.IsNullOrEmpty())
                {
                    sable = sable.Where(" (ProductSku like @productSku or ProductName like @productName or DPContent like @dpContent or NikName like @nickName) ");
                }
                if (search.Start.HasValue)
                {
                    sable = sable.Where(" AddTime >='"+search.Start.Value.ToString("yyyy-MM-dd HH:mm:ss")+"'");
                }
                if (search.End.HasValue)
                {
                    sable = sable.Where(" AddTime <='" + search.End.Value.ToString("yyyy-MM-dd HH:mm:ss") + "'");
                }
                if (!search.IP.IsNullOrEmpty())
                {
                    sable = sable.Where(" IP like '%"+search.IP+"%'");
                }

                var pars = new { productSku = "%" + search.Keywords + "%", productName = "%" + search.Keywords + "%", dpContent = "%" + search.Keywords + "%", nickName = "%" + search.Keywords + "%" };
                total = sable.Count(pars);
                var list = sable.SelectToPageList<V_Product_Comment>("*", search.OrderByFields, search.Skip / search.Take + 1, search.Take, pars);
                return list;
            }
        }

        /// <summary>
        /// 回复评论
        /// </summary>
        /// <param name="comment"></param>
        /// <param name="currentUserId"></param>
        /// <returns></returns>
        public Result CommentReply(Product_Comment comment, int currentUserId)
        {
            if (comment == null || comment.Id == 0)
            {
                return Result.Failure("该评论不存在");
            }

            using (var Db = DbConfig.GetInstance())
            {
                comment.EditTime = DateTime.Now;
                comment.EditUserId = currentUserId;
                comment.ReplyUserId = currentUserId;

                var user = Db.Queryable<UserInfo>().SingleOrDefault(t => t.Id == currentUserId);
                comment.ReplyUserName = user.UserName;
                comment.ReplyTime = DateTime.Now;
                if (Db.Update(comment))
                {
                    return Result.Success();
                }
                return Result.Failure("操作失败");
            }
        }

        /// <summary>
        /// 删除评论
        /// </summary>
        /// <param name="Id"></param>
        /// <param name="currentUserId"></param>
        /// <returns></returns>
        public Result DelComment(int Id, int currentUserId)
        {
            if (Id == 0)
            {
                return Result.Failure("该评论不存在");
            }

            using (var Db = DbConfig.GetInstance())
            {
                if (Db.Update<Product_Comment>(new { IsDeleted = true }, m => m.Id == Id))
                {
                    return Result.Success();
                }
                return Result.Failure("操作失败");
            }
        }


        #region 前台方法


        public ProductDetailResponse ProductDetail(string Sku, int ActivityId, int currentMemberId)
        {
            var response = new ProductDetailResponse();
            using (var Db = DbConfig.GetInstance())
            {
                if (!Sku.IsNullOrEmpty() && Sku != "0")
                {
                    //产品主信息
                    var product = Db.Queryable<Product>().SingleOrDefault(m => m.Sku == Sku && m.IsDisplay == true);
                    if (product == null || product.Id == 0)
                    {
                        return null;
                    }
                    product.TotalStock = 0;
                    response.ProductMain = product.ConvertTo<ProductInfo>();
                    response.ProductMain.SubImgUrls = product.ImgUrls.FromJson<List<string>>();
                    response.ProductMain.MaxPrice = Db.Queryable<Product_Spec>().Where(m => m.ProductSku == Sku && m.Stock - m.WaitSendStock > 0).ToList().Max(t => t.Price);


                    //规格信息
                    var speclist = Db.Queryable<Product_Spec>().Where(m => m.ProductSku == Sku && m.Stock - m.WaitSendStock > 0).ToList();
                    var specresponse = new List<SpecResponse>();
                    if (speclist != null && speclist.Count > 0)
                    {
                        Db.CurrentFilterKey = "";
                        speclist.ForEach(m =>
                        {
                            var specitem = m.ConvertTo<SpecResponse>();
                            specitem.SpecItemList = Db.Queryable<Product_SpecTemplateItem>().JoinTable<Product_SpecTemplate>((s, j) => s.SpecTemplateId == j.Id).In("s.Id", m.SpecIds.FromJson<List<int>>()).OrderBy<Product_SpecTemplate>((s, j) => j.Sort).ToList();
                            specitem.SpecNames = "";
                            specitem.SpecItemList.ForEach(ss => { specitem.SpecNames += ss.SpecItemName + "  "; });
                            specitem.SpecNames = specitem.SpecNames.Trim();

                            specresponse.Add(specitem);
                        });

                        response.SpecList = specresponse.OrderBy(o => o.SpecItemList[0].Id).ToList();

                        response.ProductMain.TotalStock = response.SpecList.Sum(s => s.Stock - s.WaitSendStock);
                        response.ProductMain.Price = response.SpecList.Min(s => s.Price);
                        response.ProductMain.MarketPrice = response.SpecList.Max(s => s.MarketPrice);

                        Db.CurrentFilterKey = "FalseDelte";

                        response.ShareTittle = response.ProductMain.Name;
                        response.ShareContent = response.ProductMain.Description;
                        response.ShareImg = response.ProductMain.ImgUrl;
                    }
                    //如果是抢购商品，重置数据
                    if (ActivityId > 0)
                    {
                        var spike = Db.Queryable<Activity_Spike>().SingleOrDefault(m => m.Id == ActivityId);
                        var spikespec = Db.Queryable<Activity_SpikeSpec>().SingleOrDefault(m => m.SpikeId == ActivityId && m.ProductSku == Sku);
                        //response.SpikeTimeSpans = 0;
                        if (spike.EndTime > DateTime.Now && (spike.EndTime - spike.BeginTime).TotalMilliseconds > 0)
                        {
                            response.SpikeEndTime = spike.EndTime.ToString("yyyy/MM/dd HH:mm:ss");
                        }
                        if (spike.BeginTime > DateTime.Now)
                        {
                            response.SpikeBeginTime = spike.BeginTime.ToString("yyyy/MM/dd HH:mm:ss");
                        }
                        response.SpikeLimit = spikespec.Limit;
                        response.SpecList.ForEach(m =>
                        {
                            m.Price = spikespec.Price;
                        });
                        response.ProductMain.TotalStock = spikespec.Stock - spikespec.SpikeStock;
                        response.ProductMain.Price = spikespec.Price;

                        response.ShareTittle = spike.ShareTitle;
                        response.ShareContent = spike.ShareContent;
                        response.ShareImg = spike.HeadPicUrl;

                    }


                    //购物车数量
                    response.ShopCartCount = Db.Queryable<Member_ShopCart>().Where(m => m.MemberId == currentMemberId).Count();

                    //是否收藏
                    response.IsFavorited = Db.Queryable<Member_Favorite>().Where(m => m.ProductSku == Sku && m.MemberId == currentMemberId).Count() > 0;

                }
                else
                {
                    return null;
                }


                return response;
            }
        }


        public List<ProductCommentInfo> CommentList(int Skip, int Take, string Sku, out int total)
        {
            using (var Db = DbConfig.GetInstance())
            {
                var response = new List<ProductCommentInfo>();
                total = Db.Queryable<Product_Comment>().Where(m => m.ProductSku == Sku).Count();
                var commentlist = Db.Queryable<Product_Comment>().Where(m => m.ProductSku == Sku).OrderBy(o => o.Id, OrderByType.Desc).Skip(Skip).Take(Take).ToList();
                if (commentlist != null && commentlist.Count > 0)
                {
                    commentlist.ForEach(m =>
                    {
                        var comment = m.ConvertTo<ProductCommentInfo>();
                        if (!m.ImgUrls.IsNullOrEmpty())
                        {
                            comment.ImgList = m.ImgUrls.FromJson<List<string>>();
                        }
                        response.Add(comment);
                    });
                }
                return response;
            }
        }


        public bool ProductFavorite(string Sku, int currentMemberId)
        {
            using (var Db = DbConfig.GetInstance())
            {
                var product = Db.Queryable<Product>().SingleOrDefault(m => m.Sku == Sku);

                if (Db.Queryable<Member_Favorite>().Where(m => m.ProductSku == Sku && m.MemberId == currentMemberId).Count() > 0)
                {
                    Db.Update<Member_Favorite>(new { IsDeleted = true }, m => m.ProductSku == Sku && m.MemberId == currentMemberId);
                    product.FavoriteCount = product.FavoriteCount - 1;
                    Db.Update(product);
                    return false;
                }

                Db.Insert(new Member_Favorite
                {
                    MemberId = currentMemberId,
                    ProductSku = Sku,
                    ProductName = product.Name,
                    ProductImgUrl = product.ImgUrl,
                    AddUserId = currentMemberId,
                    MarketPrice = product.MarketPrice,
                    Price = product.Price
                });
                product.FavoriteCount = product.FavoriteCount + 1;
                Db.Update(product);
                return true;
            }
        }


        public int AddShopCart(string Sku, int SpecId, int Num, int currentMemberId)
        {
            using (var Db = DbConfig.GetInstance())
            {
                var cart = Db.Queryable<Member_ShopCart>().SingleOrDefault(m => m.ProductSku == Sku && m.SpecId == SpecId && m.MemberId == currentMemberId);
                if (cart == null || cart.Id == 0)
                {
                    cart = new Member_ShopCart
                    {
                        MemberId = currentMemberId,
                        Num = Num,
                        ProductSku = Sku,
                        SpecId = SpecId
                    };
                }
                else
                {
                    cart.Num += Num;
                }
                Db.InsertOrUpdate(cart);
                return Db.Queryable<Member_ShopCart>().Where(m => m.MemberId == currentMemberId).Count();
            }
        }


        public List<CartProduct> ShopCartList(int currentMemberId)
        {
            using (var Db = DbConfig.GetInstance())
            {
                var response = new List<CartProduct>();
                var cartlist = Db.Queryable<Member_ShopCart>().Where(m => m.MemberId == currentMemberId).OrderBy(o => o.Id, OrderByType.Desc).ToList();
                if (cartlist != null && cartlist.Count > 0)
                {
                    cartlist.ForEach(m =>
                    {
                        Db.CurrentFilterKey = "";
                        var cart = m.ConvertTo<CartProduct>();

                        var product = Db.Queryable<Product>().SingleOrDefault(p => p.Sku == m.ProductSku);
                        var spec = Db.Queryable<Product_Spec>().SingleOrDefault(s => s.Id == m.SpecId);

                        cart.ProductName = product.Name;
                        if (!spec.SpecNames.IsNullOrEmpty())
                        {
                            var specnamelist = spec.SpecNames.FromJson<List<string>>();
                            if (specnamelist.Count > 0)
                            {
                                specnamelist.ForEach(n => cart.SpecNames += n + " ");
                                cart.SpecNames = cart.SpecNames.Trim();
                            }
                        }
                        cart.ImgUrl = product.ImgUrl;
                        cart.UniformFreight = product.UniformFreight;
                        cart.FreightTemplateId = product.FreightTemplateId;
                        cart.ProductWeight = spec.ProductWeight;
                        cart.Price = spec.Price;
                        cart.IsValid = false;
                        if (product.IsDeleted || !product.IsDisplay || spec.Stock - spec.WaitSendStock <= 0 || spec.IsDeleted)
                        {
                            cart.IsValid = true;
                        }

                        response.Add(cart);
                    });
                }
                return response;
            }
        }


        public List<CartProduct> GetShopCartList(string CartIds)
        {
            using (var Db = DbConfig.GetInstance())
            {
                var response = new List<CartProduct>();
                var ids = CartIds.Split(',');
                var cartlist = Db.Queryable<Member_ShopCart>().In(m => m.Id, ids).OrderBy(m => m.Id, OrderByType.Desc).ToList();
                if (cartlist != null && cartlist.Count > 0)
                {
                    cartlist.ForEach(m =>
                    {
                        Db.CurrentFilterKey = "";
                        var cart = m.ConvertTo<CartProduct>();

                        var product = Db.Queryable<Product>().SingleOrDefault(p => p.Sku == m.ProductSku);
                        var spec = Db.Queryable<Product_Spec>().SingleOrDefault(s => s.Id == m.SpecId);

                        cart.ProductName = product.Name;
                        if (!spec.SpecNames.IsNullOrEmpty())
                        {
                            var specnamelist = spec.SpecNames.FromJson<List<string>>();
                            if (specnamelist.Count > 0)
                            {
                                specnamelist.ForEach(n => cart.SpecNames += n + " ");
                                cart.SpecNames = cart.SpecNames.Trim();
                            }
                        }
                        cart.ImgUrl = product.ImgUrl;
                        cart.UniformFreight = product.UniformFreight;
                        cart.FreightTemplateId = product.FreightTemplateId;
                        cart.ProductWeight = spec.ProductWeight;
                        cart.Price = spec.Price;
                        cart.CostPrice = spec.CostPrice;
                        cart.IsValid = false;
                        if (product.IsDeleted || !product.IsDisplay || spec.Stock - spec.WaitSendStock <= 0 || spec.IsDeleted)
                        {
                            cart.IsValid = true;
                        }
                        cart.IsAllowUseCoupon = product.IsAllowUseCoupon;
                        cart.IsAllowUsePoints = product.IsAllowUsePoints;
                        cart.CategoryId = product.CategoryId;
                        cart.ProductId = product.Id;
                        cart.UsePointRate = product.UsePointRate;
                        response.Add(cart);
                    });
                }
                return response;
            }
        }


        public Result ChangeShopCartNum(int Id, int Num, int currentMemberId)
        {
            using (var Db = DbConfig.GetInstance())
            {
                Db.Update<Member_ShopCart>(new { Num = Num, EditUserId = currentMemberId, EditTime = DateTime.Now }, m => m.Id == Id);
                return Result.Success();
            }
        }


        public Result DelCart(int Id, int currentMemberId)
        {
            using (var Db = DbConfig.GetInstance())
            {
                if (Db.Update<Member_ShopCart>(new { IsDeleted = true, EditUserId = currentMemberId, EditTime = DateTime.Now }, m => m.Id == Id))
                {
                    return Result.Success();
                }
                return Result.Failure("操作失败");
            }
        }

        public Member_ShopCart GetMember_ShopCart(int Id)
        {
            using (var Db = DbConfig.GetInstance())
            {
                return Db.Queryable<Member_ShopCart>().SingleOrDefault(t => t.Id == Id);
            }
        }

        public bool DelCart(List<Member_ShopCart> list)
        {
            using (var Db = DbConfig.GetInstance())
            {
                return Db.Delete<Member_ShopCart>(list);
            }
        }


        public List<Member_Favorite> GetMyFavorite(int Skip, int Take, int currentMemberId, out int total)
        {
            using (var Db = DbConfig.GetInstance())
            {
                total = Db.Queryable<Member_Favorite>().Where(m => m.MemberId == currentMemberId).Count();
                return Db.Queryable<Member_Favorite>().Where(m => m.MemberId == currentMemberId).OrderBy(o => o.Id, OrderByType.Desc).Skip(Skip).Take(Take).ToList();
            }
        }


        public Result CancelFavorite(int Id, int currentMemberId)
        {
            using (var Db = DbConfig.GetInstance())
            {
                if (Db.Update<Member_Favorite>(new { IsDeleted = true, EditUserId = currentMemberId, EditTime = DateTime.Now }, m => m.Id == Id))
                {
                    return Result.Success();
                }
                return Result.Failure("操作失败");
            }
        }


        public List<Product> ProductList(WapProductSearchModel search, out int total)
        {
            using (var Db = DbConfig.GetInstance())
            {
                Db.CurrentFilterKey = "";
                Sqlable sable = Db.Sqlable().From<Product>("P");
                sable.Join<Product_Spec>("PS", "PS.ProductSku", "P.Sku", JoinType.Left);
                sable.Join<Product_Category>("PC", "PC.Id", "P.CategoryId", JoinType.Left);
                sable.Join<Product_Category>("PC1", "PC1.Id", "PC.ParentId", JoinType.Left);
                sable.Where(" P.IsDeleted=0 AND PS.IsDeleted=0 AND P.IsDisplay=1 ");
                if (!search.Keywords.IsNullOrEmpty())
                {
                    sable.Where(" (P.Name like @Name or P.Sku like @Sku or PS.BarCode like @BarCode) ");
                }

                if (search.fcId > 0)
                {
                    sable.Where(" PC1.Id=@FirstCategoryId ");
                    if (search.scId > 0)
                    {
                        sable.Where(" PC.Id=@SecondCategoryId ");
                    }
                }


                search.OrderByFields = "P.Sort Desc,P.Id DESC";

                var pars = new { Name = "%" + search.Keywords + "%", Sku = "%" + search.Keywords + "%", BarCode = "%" + search.Keywords + "%", FirstCategoryId = search.fcId, SecondCategoryId = search.scId };
                sable.GroupBy = "GROUP BY P.Id,P.Name,P.Sku,P.Price,P.MarketPrice,P.ImgUrl,P.Sort";
                total = sable.SelectToList<Product>("P.Id", pars).Count;
                var list = sable.SelectToPageList<Product>("P.Id,P.Name,P.Sku,P.Price,P.MarketPrice,P.ImgUrl,P.Sort", search.OrderByFields, search.Skip / search.Take + 1, search.Take, pars);
                list.ForEach(m =>
                {
                    var speclist = Db.Queryable<Product_Spec>().Where(w => w.ProductSku == m.Sku && w.IsDeleted == false && w.Stock - w.WaitSendStock > 0).ToList() ?? new List<Product_Spec>();
                    if (speclist != null && speclist.Count > 0)
                    {
                        m.Price = speclist.Min(s => s.Price);
                        m.MarketPrice = speclist.Max(s => s.MarketPrice);
                    }
                });
                return list;
            }
        }


        public List<AddCommentResponse> GetOrderComment(int orderId)
        {
            using (var Db = DbConfig.GetInstance())
            {
                var orderdetail = Db.Queryable<OrderDetail>().Where(m => m.OrderId == orderId).ToList();
                if (orderdetail == null || orderdetail.Count == 0)
                {
                    return null;
                }

                var response = new List<AddCommentResponse>();

                orderdetail.ForEach(m =>
                {
                    string specnames = "";
                    if (!m.SpecName.IsNullOrEmpty())
                    {
                        m.SpecName.FromJson<List<string>>().ForEach(s => specnames += s + " ");
                    }
                    response.Add(new AddCommentResponse
                    {
                        ImgUrlList = new List<string>(),
                        DPContent = "",
                        ProductName = m.ProductName,
                        ProductNum = m.ProductCount,
                        ProductPrice = m.ProductPrice,
                        ProductSku = m.ProductSku,
                        SpecNames = specnames,
                        ProductImgUrl = m.ImgUrl
                    });
                });
                return response;
            }
        }


        public Result OrderCommentSubmit(List<AddCommentResponse> comments, int orderId, int currentMemberId, string ip)
        {
            using (var Db = DbConfig.GetInstance())
            {
                try
                {
                    Db.IsNoLock = true;
                    Db.CommandTimeOut = 30000;//设置超时时间
                    if (comments == null || comments.Count == 0 || orderId == 0)
                    {
                        return Result.Failure("操作失败，请刷新再试");
                    }

                    var member = Db.Queryable<Member>().SingleOrDefault(m => m.Id == currentMemberId);

                    var order = Db.Queryable<Order>().SingleOrDefault(t => t.Id == orderId);

                    if (order.OrderState == OrderStatus.已完成)
                    {
                        return Result.Failure("该订单已评价");
                    }
                    else if (order.OrderState != OrderStatus.已收货)
                    {
                        return Result.Failure("收货后才能评价");
                    }
                    Db.BeginTran();
                    comments.ForEach(m =>
                    {
                        int count = Db.Queryable<Product_Comment>().Where(t => t.MemberId == currentMemberId && t.RelationId == orderId && t.ProductSku == m.ProductSku).Count();
                        if (count == 0)
                        {
                            Db.Insert(new Product_Comment
                            {
                                AddUserId = currentMemberId,
                                DPContent = m.DPContent,
                                HeadUrl = member.Avatar,
                                ImgUrls = (m.ImgUrlList ?? new List<string>()).ToJson(),
                                IP = ip,
                                MemberId = currentMemberId,
                                NikName = member.NickName,
                                ProductName = m.ProductName,
                                ProductSku = m.ProductSku,
                                RelationId = orderId,
                                CommentLevel = m.CommentLevel,
                                ReplyTime = null
                            });
                        }
                    });
                    order.OrderState = OrderStatus.已完成;
                    Db.Update<Order>(order);
                    OrderRecord or = new OrderRecord();
                    or.OrderStatus = order.OrderState;
                    or.OrderId = order.Id;
                    or.OrderNo = order.OrderNo;
                    or.PayStatus = order.PayState;
                    or.OperationId = currentMemberId;
                    or.OperationUserType = 0;
                    or.OperationNote = "用户评价订单";
                    or.ClientName = "微信";
                    or.Ip = Generator.GetIP();
                    Db.Insert(or);

                    Db.CommitTran();//提交事务
                    return Result.Success();
                }
                catch (Exception ex)
                {
                    Db.RollbackTran();//回滚事务
                    return Result.Failure(ex.Message);
                }
            }
        }

        #endregion
        /// <summary>
        /// 统计待上架的商品
        /// </summary>
        /// <returns></returns>
        public int GetStatisticsLower()
        {
            using (var Db = DbConfig.GetInstance())
            {
                var list = Db.Queryable<Model.Product>()
                   .Where(m => !m.IsDisplay&&!m.IsDeleted)
                   .ToList();
                return list.Count;
            }
        }

        /// <summary>
        /// 统计销售中的商品
        /// </summary>
        /// <returns></returns>
        public int GetStatisticsUpper()
        {
            using (var Db = DbConfig.GetInstance())
            {
                var list = Db.Queryable<Model.Product>()
                   .Where(m => m.IsDisplay&&!m.IsDeleted)
                   .ToList();
                return list.Count;
            }
        }


        /// <summary>
        /// 获取库存不足的商品
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public int GetStocNotEnoughk()
        {
            using (var Db = DbConfig.GetInstance())
            {
                var stock = 1;
                string sql1 =
                  $@"select StockWarning from SystemConfiguration";
                var dt1 = Db.GetDataTable(sql1);

                if (dt1 != null && dt1.Rows.Count>0)
                {
                    if (dt1.Rows[0] != null)
                    {
                        if (dt1.Rows[0][0] != DBNull.Value)
                        {
                            stock = Convert.ToInt32(dt1.Rows[0][0]);
                        }
                    }
                }

                string sql =
                    $@"select * from Product p inner join Product_Spec ps on p.sku=ps.ProductSku where p.isdeleted=0 and ps.isdeleted=0 and p.IsDisplay=1 and ps.Stock-ps.WaitSendStock<" + stock + " and ps.Stock-ps.WaitSendStock>0";
                var dt = Db.GetDataTable(sql);

                return dt.Rows.Count;
            }
        }

        public int GetStockEmpty()
        {
            using (var Db = DbConfig.GetInstance())
            {
                string sql =
                    $@"select * from Product p inner join Product_Spec ps on p.sku=ps.ProductSku where p.isdeleted=0 and ps.isdeleted=0 and p.IsDisplay=1 and ps.Stock-ps.WaitSendStock<=0";
                var dt = Db.GetDataTable(sql);
                return dt.Rows.Count;
            }
        }


        public Result UpdateProductArea(List<string> AidList, int ProductId, int userId)
        {
            using (var db = DbConfig.GetInstance())
            {
                db.CurrentFilterKey = "";
                AidList = AidList ?? new List<string>();

                var alllist = db.Queryable<Common_Area>().Where(t => t.Level < 3).OrderBy("Id,Sort").ToList();



                var updateAuthList =
                    alllist.Where(m => AidList.Contains(m.Id.ToString()))
                        .Select(m => m.Id.ToString()).ToList() ?? new List<string>();


                var currentAuth = db.Queryable<Product_Area>().Where(t => t.ProductId == ProductId).ToList();
                if (currentAuth != null && currentAuth.Count > 0)
                {
                    foreach (var item in currentAuth)
                    {
                        if (updateAuthList.Contains(item.AreaId.ToString()))
                        {
                            updateAuthList.Remove(item.AreaId.ToString());
                        }
                        else
                        {
                            db.Delete<Product_Area>(item);
                        }
                    }
                }

                if (updateAuthList != null && updateAuthList.Count > 0)
                {
                    List<Product_Area> l = new List<Product_Area>();
                    foreach (var Id in updateAuthList)
                    {
                        Product_Area pa = new Product_Area();
                        pa.AreaId = Id.ObjToInt();
                        pa.ProductId = ProductId;
                        pa.AddUserId = userId;

                        l.Add(pa);
                    }
                    db.InsertRange<Product_Area>(l);
                }
                return Result.Success();

            }
        }

        public bool IsCanBuy(int cityId, int productId)
        {
            using (var db = DbConfig.GetInstance())
            {
                db.CurrentFilterKey = "";
                int count = db.Queryable<Product_Area>().Where(t => t.ProductId == productId).Count();
                if (count == 0)
                {
                    return true;
                }
                count = db.Queryable<Product_Area>().Where(t => t.AreaId == cityId && t.ProductId == productId).Count();
                if (count > 0)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }
    }
}
